package cn.tedu.csmall.passport.filter;

import cn.tedu.csmall.commons.web.ServiceCode;
import cn.tedu.csmall.commons.security.LoginPrincipal;
import cn.tedu.csmall.commons.web.JsonResult;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;

@Slf4j
@Component
public class JwtAuthorizationFilter extends OncePerRequestFilter{
    @Value("${csmall.jwt.secret-key}")
    private String secretKey;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        log.debug("过滤器开始执行！。。。。。。。。。。。。。");
        String jwt = request.getHeader("Authorization");
        log.debug("客户端携带的JWT：{}", jwt);

        if (!StringUtils.hasText(jwt)) {
            filterChain.doFilter(request, response);
            return;
        }

        Claims claims = null;
        response.setContentType("application/json; charset=utf-8");
        try {
            claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwt).getBody();
        } catch (MalformedJwtException e) {
            String message = "你犯法啦！";
            log.warn("程序运行过程中出现了MalformedJwtException，将统一处理！");
            log.warn("错误信息{}", message);
            JsonResult fail = JsonResult.fail(ServiceCode.ERR_JWT_MALFORMED, message);

            String s = JSON.toJSONString(fail);

            PrintWriter writer = response.getWriter();  //流拿到了不响应后边就拿不到
            writer.println(s);
            writer.close();
            return;
        } catch (SignatureException e) {
            String message = "你犯法啦！";
            log.warn("程序运行过程中出现了SignatureException，将统一处理！");
            log.warn("错误信息{}", message);
            JsonResult fail = JsonResult.fail(ServiceCode.ERR_JWT_SIGNATURE, message);

            String s = JSON.toJSONString(fail);

            PrintWriter writer = response.getWriter();
            writer.println(s);
            writer.close();
            return;
        } catch (ExpiredJwtException e) {
            String message = "您的登陆信息已经过期，请重新登陆！";
            log.warn("程序运行过程中出现了ExpiredJwtException，将统一处理！");
            log.warn("错误信息{}", message);
            JsonResult fail = JsonResult.fail(ServiceCode.ERR_JWT_EXPIRED, message);

            String s = JSON.toJSONString(fail);

            PrintWriter writer = response.getWriter();
            writer.println(s);
            writer.close();
            return;
        } catch (Throwable e) {
            String message = "服务器忙，请稍后再试！【在开发过程中，如果看到此提示，应该检查服务器端的控制台，分析异常，并在全局异常处理器中补充处理对应异常的方法】";
            log.warn("程序运行过程中出现了Throwable，将统一处理！");
            log.warn("异常：{}", e);
            JsonResult fail = JsonResult.fail(ServiceCode.ERR_UNKNOWN, message);

            String s = JSON.toJSONString(fail);

            PrintWriter writer = response.getWriter();
            writer.println(s);
            writer.close();
            return;
        }


        Long id = claims.get("id",Long.class);
        String username = claims.get("username", String.class);
        String authoritiesJSONString = claims.get("authorities", String.class);

        Object principal = new LoginPrincipal().setId(id).setUsername(username);
        Object credentials = null;
        Collection<SimpleGrantedAuthority> authorities = JSON.parseArray(authoritiesJSONString,SimpleGrantedAuthority.class);
        Authentication authentication = new UsernamePasswordAuthenticationToken(
                principal, credentials, authorities
        );

        SecurityContext securityContext = SecurityContextHolder.getContext();
        securityContext.setAuthentication(authentication);
        log.debug("创建认证信息完成！，{}", authentication);

        filterChain.doFilter(request, response);
    }
}
